package com.soilflow.web.controller.common;


import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.utils.file.FileUploadUtils;
import com.soilflow.system.domain.QiNiuSysFile;
import com.soilflow.system.service.ISysFileService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Locale;

/**
 * 文件请求处理
 * 
 * @author
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(com.soilflow.web.controller.common.SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("/sysfile/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            String fileMd5 = DigestUtils.md5Hex(file.getInputStream()).toUpperCase(Locale.ROOT);
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            QiNiuSysFile qiNiuSysFile = new QiNiuSysFile();
            qiNiuSysFile.setSize(file.getSize());
            qiNiuSysFile.setMd5(fileMd5);
            qiNiuSysFile.setType(FileUploadUtils.getFileType(file.getContentType()));
            qiNiuSysFile.setName(file.getOriginalFilename());
            qiNiuSysFile.setUrl(url);
            System.out.println("qiNiuSysFile = " + qiNiuSysFile);
            return AjaxResult.success(qiNiuSysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}